package com.test.contract;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    ListView dataList;
    Adapter adapter;
    EditText queryTxt;
    AlertView alertView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dataList = findViewById(R.id.dataList);
        adapter = new Adapter();
        dataList.setAdapter(adapter);

        View root = LayoutInflater.from(this).inflate(R.layout.item_edit, null);
        queryTxt = root.findViewById(R.id.queryText);
        alertView = new AlertView("查询", null, "取消", new String[]{"查询"}, null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if(position != AlertView.CANCELPOSITION) {
                    String name = queryTxt.getText().toString();
                    SqlHelper sqlHelper = new SqlHelper(MainActivity.this);
                    adapter.setData(sqlHelper.getContract(name));
                    sqlHelper.close();
                }

                View focus = getCurrentFocus();
                if(focus != null) {
                    InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    manager.hideSoftInputFromWindow(focus.getWindowToken(), 0);
                    focus.clearFocus();
                }
                alertView.dismiss();
            }
        });
        alertView.addExtView(root);

        findViewById(R.id.addBtn).setOnClickListener(this);
        findViewById(R.id.editBtn).setOnClickListener(this);
        findViewById(R.id.detailBtn).setOnClickListener(this);
        findViewById(R.id.delBtn).setOnClickListener(this);
        findViewById(R.id.queryBtn).setOnClickListener(this);
        findViewById(R.id.quitBtn).setOnClickListener(this);


        SqlHelper sqlHelper = new SqlHelper(this);
        adapter.setData(sqlHelper.getContract(null));
        sqlHelper.close();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.addBtn:
                startActivityForResult(new Intent(this, AddActivity.class), 100);
                break;
            case R.id.editBtn: {
                if (adapter.getSelectBean() == null) {
                    ToastUtils.sendToast(this, "请先选择联系人");
                    return;
                }
                Intent intent = new Intent(this, AddActivity.class);
                intent.putExtra("User", adapter.getSelectBean());
                startActivityForResult(intent, 100);
                break;
            }
            case R.id.detailBtn: {
                if (adapter.getSelectBean() == null) {
                    ToastUtils.sendToast(this, "请先选择联系人");
                    return;
                }
                Intent intent = new Intent(this, DetailActivity.class);
                intent.putExtra("User", adapter.getSelectBean());
                startActivity(intent);
                break;
            }
            case R.id.delBtn:
                if(adapter.getSelectBean() == null) {
                    ToastUtils.sendToast(this, "请先选择联系人");
                    return;
                }
                SqlHelper sqlHelper = new SqlHelper(this);
                sqlHelper.delUser(adapter.getSelectBean());
                sqlHelper.close();
                adapter.removeData(adapter.getSelectBean());
                adapter.resetSelect();
                break;
            case R.id.queryBtn: {
                queryTxt.setText("");
                alertView.show();
                break;
            }
            case R.id.quitBtn:
                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 100 && data != null) {
            if(resultCode == 1) {
                adapter.updateData((User) data.getSerializableExtra("User"));
            }
            else {
                adapter.addData((User) data.getSerializableExtra("User"));
            }
        }
    }

    private static class Adapter extends BaseAdapter {
        private ArrayList<User> dataList = new ArrayList<>();
        private User selectBean;

        private Adapter() {
        }

        public User getSelectBean() {
            return selectBean;
        }

        public void resetSelect() {
            selectBean = null;
        }

        public void setData(List<User> data) {
            dataList.clear();
            dataList.addAll(data);
            notifyDataSetChanged();
        }

        public void addData(User user) {
            dataList.add(user);
            notifyDataSetChanged();
        }

        public void removeData(User user) {
            dataList.remove(user);
            notifyDataSetChanged();
        }

        public void updateData(User user) {
            int idx = -1;
            for(int i = 0 ; i < dataList.size() ; i ++) {
                if(user.getId().equals(dataList.get(i).getId())) {
                    idx = i;
                    break;
                }
            }
            if(idx == -1) {
                return;
            }
            dataList.remove(idx);
            dataList.add(idx, user);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return dataList.size();
        }

        @Override
        public Object getItem(int i) {
            return dataList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            TextView textView = null;
            if(view == null) {
                textView = (TextView) LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, viewGroup, false);
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        User user = (User) view.getTag();
                        if(selectBean != null && selectBean.getId().equals(user.getId())) {
                            selectBean = null;
                        }
                        else {
                            selectBean = user;
                        }
                        notifyDataSetChanged();
                    }
                });
            }
            else {
                textView = (TextView) view;
            }

            User user = dataList.get(i);
            if(selectBean != null && selectBean.getId().equals(user.getId())) {
                textView.setBackgroundColor(Color.RED);
            }
            else {
                textView.setBackgroundColor(Color.BLACK);
            }

            textView.setText(user.getName());
            textView.setTag(user);

            return textView;
        }
    }
}
